<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form
          ref="formRef"
          class="antd-modal-form"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          name="GbtIntegralRecordForm"
        >
          <a-row>
            <a-col :span="24">
              <a-form-item
                label="记录时间"
                v-bind="validateInfos.recordTime"
                id="GbtIntegralRecordForm-recordTime"
                name="recordTime"
              >
                <a-date-picker
                  placeholder="请选择记录时间"
                  v-model:value="formData.recordTime"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="名字"
                v-bind="validateInfos.name"
                id="GbtIntegralRecordForm-name"
                name="name"
              >
                <JSearchSelect
                  v-model:value="formData.name"
                  placeholder="请输入名字"
                  dict="gbt_integral_user,name,id"
                  async
                  allow-clear
                  @change="onUserChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="一级部门"
                v-bind="validateInfos.firstDept"
                id="GbtIntegralRecordForm-firstDept"
                name="firstDept"
              >
                <a-input v-model:value="formData.firstDept" placeholder="请输入一级部门" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="二级部门"
                v-bind="validateInfos.secondDept"
                id="GbtIntegralRecordForm-secondDept"
                name="secondDept"
              >
                <a-input v-model:value="formData.secondDept" placeholder="请输入二级部门" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="职位"
                v-bind="validateInfos.title"
                id="GbtIntegralRecordForm-title"
                name="title"
              >
                <a-input v-model:value="formData.title" placeholder="请输入职位" allow-clear></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="积分大类"
                v-bind="validateInfos.category"
                id="GbtIntegralRecordForm-category"
                name="category"
              >
                <!-- <a-input v-model:value="formData.category" placeholder="请输入积分大类" allow-clear></a-input> -->
                <a-select
                    v-model:value="formData.category"
                    placeholder="请选择积分大类"
                    allow-clear
                    :options="categoryOptions"
                    :loading="loadingCategory"
                     @change="onCategoryChange"
                  />

              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="申报类型"
                v-bind="validateInfos.project"
                id="GbtIntegralRecordForm-project"
                name="project"
              >
              <a-select
                    v-model:value="formData.project"
                    placeholder="请选择申报类型"
                    allow-clear
                    :options="projectOptions"
                    :loading="loadingProject"
                     @change="onProjectChange"
                  />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="证明材料"
                v-bind="validateInfos.supportDocuments"
                id="GbtIntegralRecordForm-supportDocuments"
                name="supportDocuments"
              >
                <a-input
                  v-model:value="formData.supportDocuments"
                  placeholder="请输入证明材料"
                  allow-clear
                ></a-input>
              </a-form-item>
            </a-col>
             <a-col :span="24">
              <a-form-item
                label="积分标准"
                v-bind="validateInfos.guxiaodouValue"
                id="GbtIntegralRecordForm-guxiaodouValue"
                name="guxiaodouValue"
              >
              {{ formData.guxiaodouValue }}
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item
                label="积分数量"
                v-bind="validateInfos.point"
                id="GbtIntegralRecordForm-point"
                name="point"
              >
                <a-input-number
                  v-model:value="formData.point"
                  placeholder="请输入积分数量"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';
import { getValueType } from '/@/utils';
import { saveOrUpdate, searchUser, getUser,getIntegralCategories,getProjectList } from '../GbtIntegralRecordStatistics.api';
import { Form } from 'ant-design-vue';
import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
import { JSearchSelect } from '/@/components/Form';

// 选中用户时触发，可以同步其他表单字段，比如部门
const onUserChange = (userid, option) => {
  // option.extra 就是完整用户数据
  getUser({ id: userid })
    .then((user) => {
      formData.name = user.name;
      formData.userid = user.userid;
      formData.firstDept = user.firstDept;
      formData.secondDept = user.secondDept;
      formData.title = user.title;
      formData.mobile = user.mobile;
    })
    .catch((err) => {
      console.error('获取用户详情失败', err);
    });
};

const categoryOptions = ref([]) // 下拉选项
const loadingCategory = ref(false)

const projectOptions = ref([])
const loadingProject = ref(false)
const projectLoaded = ref(false) // 防止重复请求
let projectMap = {} // 用来快速查找选中项目对应对象

const fetchProjects = () => {
  loadingProject.value = true
  getProjectList({ category: formData.category })
    .then(res => {
      // 假设 res 是字符串数组 ["类型A","类型B"]
      projectOptions.value = res.map(item => ({
        label: item.project,
        value: item.id
      }))
      // 构建 map 方便选中时查找
      projectMap = {}
      res.forEach(item => {
        projectMap[item.id] = item
      })
      projectLoaded.value = true
    })
    .catch(err => {
      console.error('获取申报类型失败', err)
    })
    .finally(() => {
      loadingProject.value = false
    })
}


// 选中项目时触发
const onProjectChange = (selectedValue) => {
  const integralType = projectMap[selectedValue]
  if (integralType) {
    formData.project = integralType.project // 或者直接存 id
    formData.supportDocuments = integralType.supportDocuments
    formData.guxiaodouValue = integralType.guxiaodouValue

  } else {
    formData.project = ''
     formData.guxiaodouValue = ''
    formData.point = 0
  }
}

const onCategoryChange = (selectedValue) => {
  fetchProjects()
}

// 请求后台获取积分大类列表
const fetchCategories = () => {
  loadingCategory.value = true
  getIntegralCategories(null)
    .then(res => {
      // 假设返回数据 [{id, name}]
      categoryOptions.value = res.map(item => ({
        label: item,
        value: item // 选中后赋值给 formData.category
      }))
    })
    .catch(err => {
      console.error('获取积分大类失败', err)
    })
    .finally(() => {
      loadingCategory.value = false
    })
}
onMounted(() => {
  fetchCategories()
})


const props = defineProps({
  formDisabled: { type: Boolean, default: false },
  formData: { type: Object, default: () => ({}) },
  formBpm: { type: Boolean, default: true },
});
const formRef = ref();
const useForm = Form.useForm;
const emit = defineEmits(['register', 'ok']);
const formData = reactive<Record<string, any>>({
  id: '',
  category: '',
  project: '',
  point: undefined,
  recordTime: '',
  name: '',
  userid: '',
  mobile: '',
  title: '',
  deptIds: '',
  deptNames: '',
  firstDept: '',
  secondDept: '',
  supportDocuments: '',
});
const { createMessage } = useMessage();
const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
const confirmLoading = ref<boolean>(false);
//表单验证
const validatorRules = reactive({});
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

// 表单禁用
const disabled = computed(() => {
  if (props.formBpm === true) {
    if (props.formData.disabled === false) {
      return false;
    } else {
      return true;
    }
  }
  return props.formDisabled;
});

/**
 * 新增
 */
function add() {
  edit({});
}

/**
 * 编辑
 */
function edit(record) {
  nextTick(() => {
    resetFields();
    const tmpData = {};
    Object.keys(formData).forEach((key) => {
      if (record.hasOwnProperty(key)) {
        tmpData[key] = record[key];
      }
    });
    //赋值
    Object.assign(formData, tmpData);
  });
}

/**
 * 提交数据
 */
async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  confirmLoading.value = true;
  const isUpdate = ref<boolean>(false);
  //时间格式化
  let model = formData;
  if (model.id) {
    isUpdate.value = true;
  }
  //循环数据
  for (let data in model) {
    //如果该数据是数组并且是字符串类型
    if (model[data] instanceof Array) {
      let valueType = getValueType(formRef.value.getProps, data);
      //如果是字符串类型的需要变成以逗号分割的字符串
      if (valueType === 'string') {
        model[data] = model[data].join(',');
      }
    }
  }
  await saveOrUpdate(model, isUpdate.value)
    .then((res) => {
      if (res.success) {
        createMessage.success(res.message);
        emit('ok');
      } else {
        createMessage.warning(res.message);
      }
    })
    .finally(() => {
      confirmLoading.value = false;
    });
}

defineExpose({
  add,
  edit,
  submitForm,
});
</script>

<style lang="less" scoped>
.antd-modal-form {
  padding: 14px;
}
</style>
